﻿using Autodesk.AutoCAD.DatabaseServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Galaxy.AutoCAD.Tests
{
    public static class Tools
    {
        public static ObjectId AddToModelSpace(this Database db, Entity ent)
        {
            ObjectId entId = ObjectId.Null;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                DBObject dBBlkTbl = trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTable bt = dBBlkTbl as BlockTable;
                if (bt != null)
                {
                    DBObject dBBlkTblRcd = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    BlockTableRecord btr = dBBlkTblRcd as BlockTableRecord;
                    if (btr != null)
                    {
                        entId = btr.AppendEntity(ent);
                        trans.AddNewlyCreatedDBObject(ent, true);
                        trans.Commit();
                    }
                }
            }
            return entId;
        }
        public static ObjectIdCollection AddToModelSpace(this Database db, params Entity[] ents)
        {
            ObjectIdCollection ids = new ObjectIdCollection();
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                if (bt != null)
                {
                    BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    if (btr != null)
                    {
                        ObjectId entId = ObjectId.Null;
                        foreach (Entity outEnt in ents)
                        {
                            entId = btr.AppendEntity(outEnt);
                            trans.AddNewlyCreatedDBObject(outEnt, true);
                            ids.Add(entId);
                        }
                    }
                }
                trans.Commit();
            }
            return ids;
        }
    }
}
